package com.huayun.plugin.controller;

import com.huayun.plugin.common.TraceId;
import com.huayun.plugin.domain.RequestMeasureData;
import com.huayun.plugin.service.MeasureCableService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

@Tag(name = "线束测量导出")
@Controller
@RequestMapping("/segmentMeasure")
public class MeasureCableExportController {
    private final MeasureCableService measureCableService;

    public MeasureCableExportController(MeasureCableService measureCableService) {
        this.measureCableService = measureCableService;
    }

    @Operation(summary = "导出测量结果")
    @PostMapping("/exportBom")
    public StreamingResponseBody exportBomExcel(@RequestBody RequestMeasureData requestData,
                                                @RequestHeader("x-trace-id") String traceId,
                                                HttpServletResponse response) throws IOException {
        TraceId.set(traceId);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment");

        return outputStream -> {
            try (InputStream inputStream = Files.newInputStream(measureCableService.createMeasureFile(requestData).toPath())) {
                FileCopyUtils.copy(inputStream, outputStream);
            } finally {
                outputStream.close();
            }
        };
    }
}
